package pri.damai.xiaowu.order.server.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.io.IOException;
import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * MVC 配置
 * @Desc
 * @Author DaMai
 * @Date 2021/1/22 17:32
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    @Value("${spring.jackson.date-format}")
    private String pattern;

    /**
     * 配置 MVC 的 HTTP消息转化
     * @apiNote 把 StringOrMappingJackson2HttpMessageConverter 设置在第一位
     * @param converters
     * @return void
     * @author DaMai
     * @date 2021/1/22 17:45
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        StringOrMappingJackson2HttpMessageConverter converter = new StringOrMappingJackson2HttpMessageConverter();

        this.addObjectMapperFor(converter);

        converters.add(0, converter);

        super.extendMessageConverters(converters);
    }

    /**
     * 兼容处理处理返回值是String的情况
     *
     * @author DaMai
     * @date 2020/11/6 19:23
     */
    public static class StringOrMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {

        private static final StringHttpMessageConverter SHMC = new StringHttpMessageConverter();

        @Override
        public boolean canWrite(Class<?> clazz, MediaType mediaType) {

            boolean canWrite = super.canWrite(mediaType);

            if (!canWrite) {
                // 判断类继承
                canWrite = clazz.isAssignableFrom(String.class);
            }

            return canWrite;
        }

        @Override
        protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {

            if (object instanceof String) {
                outputMessage.getHeaders().setContentType(MediaType.TEXT_PLAIN);
                SHMC.write((String) object, MediaType.TEXT_PLAIN, outputMessage);
                return;
            }
            outputMessage.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            super.writeInternal(object, object.getClass(), outputMessage);
        }
    }

    /**
     * JackSon序列化的相关配置
     * @apiNote [描述此方法]
     * @param converter
     * @author DaMai
     * @date 2020/12/2 20:10
     */
    public void addObjectMapperFor(StringOrMappingJackson2HttpMessageConverter converter) {

        ObjectMapper objectMapper = new ObjectMapper();
        // 空对象不报错
        objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        objectMapper.configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true);

        JavaTimeModule javaTimeModule = new JavaTimeModule();
        // LocalDataTime 的序列化和反序列化
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern)));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(pattern)));

        objectMapper.registerModule(javaTimeModule);
        converter.setObjectMapper(objectMapper);
    }

    /**
     * 指定静态资源路径
     * @apiNote 发现如果继承了WebMvcConfigurationSupport，则在yml中配置的相关内容会失效。 需要重新指定静态资源
     * @param registry
     * @return void
     * @author DaMai
     * @date 2021/1/22 17:47
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //registry.addResourceHandler("doc.html").addResourceLocations("classpath*:/META-INF/resources/");
        registry.addResourceHandler("/swagger-ui/**").addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
        registry.addResourceHandler("/swagger-ui").addResourceLocations("forward:/swagger-ui/index.html");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath*:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }

}
